package com.xr.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xr.constant.MessageConstant;
import com.xr.exception.CustomException;
import com.xr.mapper.MemberMapper;
import com.xr.mapper.OrderMapper;
import com.xr.mapper.SetMealMapper;
import com.xr.pojo.*;
import com.xr.query.QueryPageBean;
import com.xr.result.PageResult;
import com.xr.service.SetMealService;
import com.xr.utils.DateUtils;
import com.xr.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
public class SetMealServiceImpl implements SetMealService {

    //本地注入
    @Autowired
    private SetMealMapper setMealMapper;


    //本地注入
    @Autowired
    private MemberMapper memberMapper;

    //本地注入
    @Autowired
    private OrderMapper orderMapper;

    //本地注入freeMarkerConfig
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_path}")
    private String out_put_path;


    private void generateHtml(String templateName, String
            outputPath, Map<String, Object> map) {
        //1.创建配置类
        Configuration configuration = freeMarkerConfig.getConfiguration();
        //2.加载模板
        Template template = null;
        BufferedWriter bw = null;
        try {
            template = configuration.getTemplate(templateName);
            //3.创建数据模型
            //4.创输出文件路径对象
            bw = new BufferedWriter(new OutputStreamWriter(new
                    FileOutputStream(outputPath), "utf-8"));
            //5.将数据填充到模板
            template.process(map, bw);
            //6.刷新缓冲流
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            //7.关闭Writer对象
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //b.生成套餐列表、套餐具体详情静态页面
    private void generateMobileStaticHtml(){
        System.out.println("生成静态页面.....");
        //2.准备套餐列表页面的数据
        List<SetMeal> setMealList=setMealMapper.selectByExample(null);
        //b.1 需要生成套餐列表页面（一个）
        generateSetMealListHtml(setMealList);
        //b.2 需要生成套餐详情页面(多个)
        generateSetMealDetailsHtml(setMealList);
    }
    //b.1 生成套餐列表静态页面
    private void generateSetMealListHtml(List<SetMeal> setMealList){
        System.out.println("生成静态页面1.....");
        setMealList.forEach(s->{
            s.setImg(QiNiuUtils.DOMAIN+s.getImg());
        });
        Map map = new HashMap();
        map.put("setmealList",setMealList);
        generateHtml("mobile_setmeal.ftl",out_put_path+"mobile_setmeal.html",map);
    }
    //b.2 生成套餐详情页面(多个)
    private void generateSetMealDetailsHtml(List<SetMeal> setMealList){
        System.out.println("生成静态页面2.....");

        for (SetMeal setMeal:setMealList) {
            Map map = new HashMap();
            map.put("setmeal",setMeal);
            map.put("setmeal",setMealMapper.SelectByFive(setMeal.getId()));
//            setMeal.setImg(QiNiuUtils.DOMAIN+setMeal.getImg());
            generateHtml("mobile_setmeal_detail.ftl",out_put_path+"mobile_setmeal_detail_"+setMeal.getId()+".html",map);
        }
//        setMealList.forEach(s->{
//            SetMeal setMeal = setMealMapper.SelectByFive(s.getId());
//            setMeal.setImg(QiNiuUtils.DOMAIN+setMeal.getImg());
//            Map map = new HashMap();
//            map.put("setmeal",setMeal);
//            generateHtml("mobile_setmeal_detail.ftl",out_put_path+"mobile_setmeal_detail_"+s.getId()+".html",map);
//        });
    }


    //热门套餐:前四条
    @Override
    public Map<String, Object> getBusinessReportData() {
        Map<String,Object> map = new HashMap<>();

        //获取当前日期
        Date today = DateUtils.getToday();
        map.put("reportDate",today);

        MemberExample me = new MemberExample();
        MemberExample.Criteria mec = me.createCriteria();
        mec.andRegtimeEqualTo(today);;

        //总会员数
        long totalMember = memberMapper.countByExample(null);

        //今日新增会员数
        long todayNewMember = memberMapper.countByExample(me);


        //本周新增会员数
        MemberExample me2 = new MemberExample();
        MemberExample.Criteria mec2 = me2.createCriteria();
        mec2.andRegtimeGreaterThanOrEqualTo(DateUtils.getThisWeekMonday());
        long thisWeekNewMember = memberMapper.countByExample(me2);

        //本月新增会员数
        MemberExample me3 = new MemberExample();
        MemberExample.Criteria mec3 = me3.createCriteria();
        mec2.andRegtimeGreaterThanOrEqualTo(DateUtils.getFirstDay4ThisMonth());
        long thisMonthNewMember = memberMapper.countByExample(me3);

        //今日预约数

        OrderExample oe = new OrderExample();
        OrderExample.Criteria oec = oe.createCriteria();
        oec.andOrderdateEqualTo(today);
        long todayOrderNumber = orderMapper.countByExample(oe);

        //本周预约数

        OrderExample oe2 = new OrderExample();
        OrderExample.Criteria oec2 = oe2.createCriteria();
        oec2.andOrderdateGreaterThanOrEqualTo(DateUtils.getThisWeekMonday());
        long thisWeekOrderNumber = orderMapper.countByExample(oe2);

        //本月预约数
        OrderExample oe3 = new OrderExample();
        OrderExample.Criteria oec3 = oe3.createCriteria();
        oec3.andOrderdateGreaterThanOrEqualTo(DateUtils.getFirstDay4ThisMonth());
        long thisMonthOrderNumber = orderMapper.countByExample(oe3);

        //今日到诊数

        OrderExample oe4 = new OrderExample();
        OrderExample.Criteria oec4 = oe4.createCriteria();
        oec4.andOrderstatusEqualTo("已到诊");
        oec4.andOrderdateEqualTo(today);
        long todayVisitsNumber = orderMapper.countByExample(oe4);


        //本周到诊数
        OrderExample oe5 = new OrderExample();
        OrderExample.Criteria oec5 = oe5.createCriteria();
        oec5.andOrderstatusEqualTo("已到诊");
        oec5.andOrderdateGreaterThanOrEqualTo(DateUtils.getThisWeekMonday());
        long thisWeekVisitsNumber = orderMapper.countByExample(oe5);

        //本月到诊数
        OrderExample oe6 = new OrderExample();
        OrderExample.Criteria oec6 = oe6.createCriteria();
        oec6.andOrderstatusEqualTo("已到诊");
        oec6.andOrderdateGreaterThanOrEqualTo(DateUtils.getFirstDay4ThisMonth());
        long thisMonthVisitsNumber = orderMapper.countByExample(oe6);

        //热门套餐（取前4）
        List<Map<String, Object>> hotSetmeal = setMealMapper.findHotSetmeal();

        map.put("reportDate",today);
        map.put("todayNewMember",todayNewMember);
        map.put("totalMember",totalMember);
        map.put("thisWeekNewMember",thisWeekNewMember);
        map.put("thisMonthNewMember",thisMonthNewMember);
        map.put("todayOrderNumber",todayOrderNumber);
        map.put("todayVisitsNumber",todayVisitsNumber);
        map.put("thisWeekOrderNumber",thisWeekOrderNumber);
        map.put("thisWeekVisitsNumber",thisWeekVisitsNumber);
        map.put("thisMonthOrderNumber",thisMonthOrderNumber);
        map.put("thisMonthVisitsNumber",thisMonthVisitsNumber);
        map.put("hotSetmeal",hotSetmeal);


        return map;
    }

    //获取套餐的预约数量
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealMapper.findSetmealCount();
    }

    @Override
    //条件查询加分页
    public PageResult findPage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), true);
        Page<SetMeal> page = setMealMapper.FindBYString(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(), page.getResult());
    }

    //添加
    @Override
    public void addSetMealCheckGroup(SetMeal meal, Integer[] checkGroupIds) {
        //1.除了检查组的数据需要新增
        setMealMapper.insertSelective(meal);
        //1.1 需要修改SQL代码，返回id值
        int mealId = meal.getId();
        //2.检查组和套餐的第三方表的数据也需要新增
        if (checkGroupIds != null && checkGroupIds.length > 0) {
            setMealMapper.addSetMealCheckGroup(mealId, checkGroupIds);
        }

        generateMobileStaticHtml();
    }

    //通过套餐管理id选中检查组id
    @Override
    public List<Integer> selectSetMealBYGroup(Integer setmeal_id) {
        return setMealMapper.selectSetMealBYGroup(setmeal_id);
    }

    //根据id查询
    @Override
    public SetMeal findById(Integer id) {
        return setMealMapper.selectByPrimaryKey(id);
    }

    @Override
    public SetMeal queryById(Integer id) {
        return setMealMapper.selectByPrimaryKey(id);
    }

    //五表联查1
    @Override
    public SetMeal QueryById(Integer id) {
        return setMealMapper.SelectByFive(id);
    }

    //五表联查2
    @Override
    public SetMeal QueryById2(Integer id) {

        return setMealMapper.queryDetailsById(id);
    }

    //五表联查3
    @Override
    public SetMeal QueryById3(Integer id) {
        // 查询套餐信息
        SetMeal setMeal = setMealMapper.selectByPrimaryKey(id);
        // 查询套餐下的检查组
        List<CheckGroup> checkGroups =
                setMealMapper.findCheckGroupListBySetmealId(id);
        if (null != checkGroups) {
            for (CheckGroup checkGroup : checkGroups) {
                // 通过检查组id检查检查项列表
                List<CheckItem> checkItems =
                        setMealMapper.findCheckItemByCheckGroupId(checkGroup.getId());
                // 设置这个检查组下所拥有的检查项
                checkGroup.setCheckItems(checkItems);
            }
            //设置套餐下的所拥有的检查组
            setMeal.setCheckGroups(checkGroups);
        }
        return setMeal;
    }

    //删除
    @Override
    public Integer DelSetMeal(Integer id) throws CustomException {
        Integer count = setMealMapper.isUseInSetMeal(id);
        if (count > 0) {
            throw new CustomException(MessageConstant.SetMeal_IN_USE);
        } else {
            setMealMapper.delSetMealAndGroup(id);
            return setMealMapper.deleteByPrimaryKey(id);
        }
    }

    //修改
    @Override
    public void update(SetMeal meal, Integer[] groupIds) {
        setMealMapper.updateByPrimaryKeySelective(meal);
        setMealMapper.delSetMealAndGroup(meal.getId());

        if (groupIds != null && groupIds.length > 0) {
            setMealMapper.addSetMealCheckGroup(meal.getId(), groupIds);
        }

    }

    //查询所有
    @Override
    public List<SetMeal> findAll() {
        return setMealMapper.selectByExample(null);
    }
}
